﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using EHR.Common;
using System.Windows.Media.Imaging;
using CommunitySystem.SystemService;
using System.IO.IsolatedStorage;
using System.Windows.Browser;

namespace CommunitySystem
{
    public partial class Login : UserControl
    {
        public static event EventHandler<LoginCompletedArgs> LoginCompleted;
        SystemService.SystemServiceClient Client = new SystemServiceClient();
        private IsolatedStorageSettings appSettings = null;
        #region 本地存储用户名密码的Key
        private const string USERNAME = "username";
        private const string PASSWORD = "password";
        #endregion
        public Login()
        {
            InitializeComponent();
            Session.dog.PropertyChanged -= new System.ComponentModel.PropertyChangedEventHandler(dog_PropertyChanged);            
            Session.dog.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(dog_PropertyChanged);            
            appSettings = IsolatedStorageSettings.ApplicationSettings;
            if (appSettings.Contains(Session.LOGINUSER) && appSettings[Session.LOGINUSER] != null && LoginCompleted != null)
            {
                LoginCompleted(this, new LoginCompletedArgs(appSettings[Session.LOGINUSER] as UserInfo));
            }

            #region 获取本地存储登录信息
            if (appSettings.Contains(USERNAME))
            {
                string um = appSettings[USERNAME].ToString();
                txtAccountName.Text = um;
                CBUsername.IsChecked = true;
            }

            if (appSettings.Contains(PASSWORD))
            {
                string password = appSettings[PASSWORD].ToString();
                txtPwd.Password = password;
                CBPassword.IsChecked = true;
            }
            
            #endregion

        }

        void dog_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if(e.PropertyName.Equals("HasDog") && Session.NeedPasswordDog){
                PassWordDog dog = sender as PassWordDog;
                if (dog.HasDog)
                {
                    SilverlightMessageBoxLibrary.Message.InfoMessage("密码狗已插入！");
                }
                //else
                //{
                //    SilverlightMessageBoxLibrary.Message.InfoMessage("密码狗已拔出！");
                //}
            }
        }
        
        private void btnLogin_Click(object sender, RoutedEventArgs e)
        {
            UserLogin();
        }

        private void BeginLogin()
        {
            errPnl.Opacity = 0;
            tbMsg.Visibility = Visibility.Visible;
            btnLogin.IsEnabled = false;
        }

        private void EndLogin()
        {
            tbMsg.Visibility = Visibility.Collapsed;
            btnLogin.IsEnabled = true;
        }

        private bool Validate()
        {
            if (Session.NeedPasswordDog)
            {                
                if (!Session.dog.HasDog)
                {
                    SilverlightMessageBoxLibrary.Message.ErrorMessage("请插入密码狗!");
                    return false;
                }
                HtmlPage.Window.Invoke("LoadPasswordDog", null);
                if (string.IsNullOrEmpty(Session.dog.Password))
                {                   
                    SilverlightMessageBoxLibrary.Message.ErrorMessage("请输入密码狗密码,然后重新登录!");                   
                    return false;
                }
            }

            if (appSettings.Contains(PASSWORD))
            {
                appSettings.Remove(PASSWORD);
            }
            if (appSettings.Contains(USERNAME))
            {
                appSettings.Remove(USERNAME);
            }


            txtAccountName.Text = txtAccountName.Text.Trim();
            if (txtAccountName.Text == "")
            {
                SetValidateMessage("请输入用户名！");
                txtAccountName.Focus();
                return false;
            }

            if (txtPwd.Password == "")
            {
                SetValidateMessage("请输入密码！");
                txtPwd.Focus();
                return false;
            }
           
            return true;
        }

        private void SetValidateMessage(string msg)
        {
            if (string.IsNullOrEmpty(msg))
            {
                errPnl.Opacity = 0;
            }
            else
            {
                errorMsg.Text = msg;
                errPnl.Opacity = 1;
            }
        }

        private void UserLogin()
        {
            if (!Validate())
            {
                return;
            }
            Client.LoginCompleted -= Client_LoginCompleted;
            Client.LoginCompleted += Client_LoginCompleted;
            Client.LoginAsync(txtAccountName.Text, txtPwd.Password, Session.dog.DateString, "", Session.NeedPasswordDog);
            //Client.LoginAsync(txtAccountName.Text, txtPwd.Password, Session.dog.DateString, txtIKey.Text, Session.NeedPasswordDog);
            BeginLogin();
        }

        void Client_LoginCompleted(object sender, LoginCompletedEventArgs e)
        {
            try
            {
                //if(e.Result == null)
                //    SilverlightMessageBoxLibrary.Message.e
                //if (e.Result.UserID > 0)
                //{
                   

                    LoginResult(e.Result);
                //}else
                //{
                //    SilverlightMessageBoxLibrary.Message.ErrorMessage("Ikey错误,错误信息:" + e.Result.LoginName + ":" +
                //                                                      e.Result.RealName);
                //}


            }
            catch (Exception ex)
            {
               
                MessageBox.Show("无法链接服务器，可能原因:\n\t"+ ex.Message);
                
            }
            EndLogin();
        }

        //void client_LoginCompleted(object sender, LoginCompletedEventArgs e)
        //{
            
        //}

        private void LoginResult(UserInfo result)
        {
            if (result == null)
            {
                SetValidateMessage("用户名或者密码错！");
                return;
            }
            #region 存储登录信息
            if (CBPassword.IsChecked == true)
            {
                if (!appSettings.Contains(USERNAME))
                {
                    appSettings.Add(USERNAME, this.txtAccountName.Text.Trim());
                }
                else
                {
                    appSettings[USERNAME] = this.txtAccountName.Text.Trim();
                }
                if (!appSettings.Contains(PASSWORD))
                {
                    appSettings.Add(PASSWORD, this.txtPwd.Password.Trim());
                }
                else
                {
                    appSettings[PASSWORD] = this.txtPwd.Password.Trim();
                }
            }
            else if (CBUsername.IsChecked == true)
            {
                if (!appSettings.Contains(USERNAME))
                {
                    appSettings.Add(USERNAME, this.txtAccountName.Text.Trim());
                }
                else
                {
                    appSettings[USERNAME] = this.txtAccountName.Text.Trim();
                }
                if (appSettings.Contains(PASSWORD))
                {
                    appSettings.Remove(PASSWORD);
                }
            }
            else
            {
                if (appSettings.Contains(PASSWORD))
                {
                    appSettings.Remove(PASSWORD);
                }
                if (appSettings.Contains(USERNAME))
                {
                    appSettings.Remove(USERNAME);
                }
            }

            #endregion
            SetValidateMessage("");

            if (LoginCompleted != null)
            {
                LoginCompleted(this, new LoginCompletedArgs(result));
            }
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            System.Windows.Browser.HtmlPage.Plugin.Focus();
            txtAccountName.Focus();
            if (Session.LastLoginName != "")
            {
                txtAccountName.Text = Session.LastLoginName;
                txtPwd.Focus();
            }

            sbLoginBoxEnter.Begin();

            refLockImgBrush.ImageSource = new WriteableBitmap(lockImg, null);
            refloginBoxImgBrush.ImageSource = new WriteableBitmap(loginBox, null);
        }

        private void UserControl_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                UserLogin();
            }
        }

        private void CBPassword_Click(object sender, RoutedEventArgs e)
        {
            if (CBPassword.IsChecked == true)
            {
                CBUsername.IsChecked = true;
            }
        }
    }

    public class LoginCompletedArgs : EventArgs
    {
        public UserInfo User;
        public LoginCompletedArgs(UserInfo user)
        {
            User = user;
        }
    }
}
